//
//  WBPhotoView.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/8.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
/*

配图微博

*/

import UIKit
import SDWebImage
//定义布局使用的宏
let WBPhotoViewMargin: CGFloat = 10 //左间距
let WBPhotoItemMargin: CGFloat = 5  //顶部间距
let WBPhotoViewItemWH: CGFloat = (UIScreen.mainScreen().bounds.width - 2 *
    WBPhotoViewMargin - 2 * WBPhotoItemMargin) / 3 //显示图片宽和高

let WBPhotoViewIdentifier = "WBPhotoViewIdentifier"
class WBPhotoView: UICollectionView ,UICollectionViewDataSource
{
    
    //拥有数据模型的类
    var pic_urls:[WBPhotoViewModel]? {
        
        didSet {
            //显示图片的数量
            //label.text = "\(pic_urls?.count)"
            //更新约束
            self.snp_updateConstraints { (make) -> Void in
                
                //得到图片数量时机找到了 在此设置显示图片的尺寸改变
                let size = calViewSize()
                
                make.width.equalTo(size.width)
                make.height.equalTo(size.height)
                
            }
            //赋值之后重新加载数据
            reloadData()
        }
        
    }
    
    
    var flowLaout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: flowLaout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI() {
        //设置数据源
        dataSource = self
        //设置代理
        delegate = self
        
        //注册cell
        registerClass(WBPhotoViewCell.self, forCellWithReuseIdentifier: WBPhotoViewIdentifier)
        flowLaout.itemSize = CGSizeMake(WBPhotoViewItemWH,WBPhotoViewItemWH)
        flowLaout.minimumInteritemSpacing = WBPhotoItemMargin //行间距
        flowLaout.minimumLineSpacing = WBPhotoItemMargin //列间距
    }
    
    
    //计算视图大小的方法
    private func calViewSize() -> CGSize {
        
        guard let count = pic_urls?.count else {
            return CGSizeZero
            
        }
        guard let count1 = pic_urls?.count where count1 != 0 else {return CGSizeZero}
        
        if count == 1 {
            //1.出现 的问题 图片的大小 和itemSzie大小不一致
            //2.图片太小 先改宽 先固定一个宽度 
            //3. 宽高比 失衡
            //获取图片 
            let url = pic_urls?.first?.photo?.thumbnail_pic
            let  image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url)
        
            //判断是否为空
            if image == nil {
             //默认宽和高
                return CGSizeMake(WBPhotoViewItemWH, WBPhotoViewItemWH)
            
            }else {
                //处理图片太窄的问题
                var size = image.size
                if size.width < 100 {
                  //系数
                  let ratio = 100 / size.width
                    
                 size.height = ratio * size.height
                    
                    size.width = 100
                }
                
            //处理图片太长的问题
                if size.height > 300 {
                  
                    size.height = 300
                }
                
                //在返回之前修改一下item
                flowLaout.itemSize = size
                 return size
            }
            
            
        }else {
        
             flowLaout.itemSize = CGSizeMake(WBPhotoViewItemWH, WBPhotoViewItemWH)
        }
        
        //四张图片显示
        if count == 4 {
            
            return CGSizeMake(2 * WBPhotoViewItemWH + WBPhotoItemMargin, 2 * WBPhotoViewItemWH + WBPhotoItemMargin)
        }
        
        
        let row = (count - 1 ) / 3 + 1
        
        return CGSizeMake(WBUIScreenW - 2 * WBPhotoViewMargin , (WBPhotoViewItemWH + WBPhotoItemMargin) * CGFloat(row))
       }
    
       ///测试lable
      //private  lazy var label:UILabel = UILabel()
}


//MARK: - 数据源方法
extension WBPhotoView:UICollectionViewDelegate {
    //返回多少组的方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //强制解包
        return pic_urls?.count ?? 0
        
    }
    
    //每个格子显示的内容
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBPhotoViewIdentifier, forIndexPath: indexPath) as! WBPhotoViewCell
        
        //设置数据
        cell.photo = pic_urls![indexPath.item]
        
        return cell
    }
    
    //点击了具体行cell的触发方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //实例
       let brower = SDPhotoBrowser()
        //代理
        brower.delegate = self
        //设置属性
        brower.sourceImagesContainerView = self
        //设置原图的数量
        brower.imageCount = (pic_urls?.count)!
        //当期展示图片
        brower.currentImageIndex = indexPath.item
        //展示图片浏览器
        brower.show()
    }
    
}

//MARK: - 第三方-SDPhotoBrowserDelegate
extension WBPhotoView: SDPhotoBrowserDelegate {

    //返回高质量图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
      let urlStr = pic_urls![index].photo!.thumbnail_pic
        
       //替换图片url一段参数可以高清显示图片
        //http:ww3.sinaimg.cn/thumbnail/70d923a0gw1f3y42nl89wj209m0byt9n.jpg
      let replaceStr = urlStr?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        
        return NSURL(string: replaceStr!)
    }

     //返回高清图片显示
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
    
        //得到原来的小图
        let index = NSIndexPath(forItem: index, inSection: 0)
        
        let cell = self.cellForItemAtIndexPath(index) as? WBPhotoViewCell
        
        return cell?.iconImageView.image
    }

}


// MARK: - cell的代理方法
class WBPhotoViewCell: UICollectionViewCell {
    
    var photo:WBPhotoViewModel? {
        
        didSet{
            //使用框架下载图片
            iconImageView.sd_setImageWithURL(photo?.thumbnail_pic)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    
    /// 添加子控件
    func setupUI() {
        addSubview(iconImageView)
        
        iconImageView.frame = bounds
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
   
   /// 懒加载展示图片
   private lazy var iconImageView: UIImageView = {
    
     let img = UIImageView()
      /*
        case ScaleToFill
        case ScaleAspectFit
        case ScaleAspectFill
      */
       //填充
      img.contentMode = .ScaleAspectFill
    
       return img
    }()
    
}